package com.example.mybaties.testone.compare;

import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringComparator implements Comparator<String> {

    @Override
    public int compare(String str1, String str2) {
        //第一步处理，不包含-的都加上-0
        if (!str1.contains("-")) {
            str1 = str1 + "-0";
        }
        if (!str2.contains("-")) {
            str2 = str2 + "-0";
        }
        //不满足指定的样式，直接使用默认的进行比较
        if (!matches(str1) || !matches(str2)) {
            return str1.compareTo(str2);
        }
        //满足指定的样式，采用下面的方式进行比较
        String[] arr1 = str1.split("-");
        String[] arr2 = str2.split("-");
        if (arr1[0].compareTo(arr2[0]) == 0) {
            int tmp1 = Integer.parseInt(arr1[1]);
            int tmp2 = Integer.parseInt(arr2[1]);
            return tmp1 - tmp2;
        } else {
            return arr1[0].compareTo(arr2[0]);
        }

    }

    /**
     * 使用正则表达式进行匹配，看是否满足
     */
    private boolean matches(String str) {
        Pattern pattern = Pattern.compile("[a-zA-Z0-9]+-[0-9]+");
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }

}
